package com.uni.config.shiro;

import com.uni.pojo.Perm;
import com.uni.pojo.Role;
import com.uni.pojo.User;
import com.uni.service.PermService;
import com.uni.service.RoleService;
import com.uni.service.UserService;
import com.uni.utils.ApplicationContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * Author:      Unirithe/Mr.Chao
 * CSDN:        https://blog.csdn.net/Unirithe
 * CreatedTime:  2022/2/9 9:57
 **/
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermService permService;
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String principal = (String) principalCollection.getPrimaryPrincipal();
        // 获取当前的用户信息
        User user = userService.getUserByCode(principal);
        if(user != null){
            // 获取用户的角色
            Role role = roleService.queryRoleByUserCode(user);
            user.setRole(role);
            // 赋予当前用户对应的角色信息（相同角色的权限是一致的）
            if(role != null) {
                info.addRole(role.getRoleName());
                // 添加权限
                List<Perm> perms = permService.queryPermByRole(role);
                if(perms!=null && !CollectionUtils.isEmpty(perms)) {
                    perms.forEach(perm -> {
                        info.addStringPermission(perm.getUrl());
                    });
                }
            }
        }
        return info;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        // 获取身份信息
        String principal = (String) token.getPrincipal();
        // 在工厂中获取Service对象
//        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        // 调用业务层，获取数据库里对应的用户信息
        User user = userService.getUserByCode(principal);
        if(!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(
                    user.getCode(),
                    user.getPassword(),
                    ByteSource.Util.bytes(user.getSalt()),
                    this.getName());
        }
        else return null;
    }
}
